from stark.service.v1 import StarkModelForm
from ..models import Contract, House


class ContractModelForm(StarkModelForm):
    class Meta:
        model = Contract
        
        fields = '__all__'
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        request = kwargs.pop("request", None)
        if request:
            roles = request.tracer.roles
            user = request.tracer.user

        if "管理员" in roles:
            return  # 管理员拥有全部权限，不做限制

        if "房东" in roles:
            # 房东只能选择自己作为房东
            self.fields["landlord"].choices = [(user.id, user.name)]
        else:
            # 按需导入Q对象
            from django.db.models import Q
    
            # 获取关联的房东
            landlord_contracts = Contract.objects.filter(
                Q(landlord=user.id) | Q(tenant=user.id)
            ).values_list('landlord_id', 'landlord__name').distinct()
    
            landlord_choices = list(landlord_contracts)

            if landlord_choices:
                self.fields["landlord"].choices = landlord_choices
                return
            # 将错误添加到form，而不是直接抛出异常
            # 第一个参数为字段名（None表示表单级错误），第二个参数为错误信息
            # from django.core.exceptions import ValidationError
            # self.add_error("landlord", "你没有房源权限")
            # raise ValidationError("无可用房源权限")

            # 可以设置一个空选项避免表单验证错误
            self.fields["landlord"].choices = [("", "无可用房源权限")]
